package com.study;

import com.study.entity.Car;
import com.study.entity.User;

import java.io.*;

public class DeepCopy01 {

    public static <T> T deepCopy(T obj, Class<T> t) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(obj);
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        T car1 = (T) ois.readObject();
        return car1;
    }

    /**
     * 方法三：使用Java自带的流方式实现
     * 优点：
     * 1.不破坏类的封装，无需了解被copy对象的内部
     * 2.不需要依赖第三方包
     * 3.代码可复用
     * 缺点：
     * 1.需要实现Serializable接口，会有额外的开销
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        User user = new User();
        user.setUsername("Tom");
        user.setPassword("123");
        Car car = new Car();
        car.setUser(user);
        car.setBland("Tesla");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(car);
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        Car car1 = (Car) ois.readObject();
        User user1 = car1.getUser();

        Car car2 = deepCopy(car, Car.class);
        User user2 = car2.getUser();
        System.out.println();
    }
}
